﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace TaskCompletionSource
{
    class Program
    {
        /// <summary>
        /// 使用TaskCompletionSource创建的Task不会占用线程
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {

            
            var tcs = new TaskCompletionSource<int>();
                tcs.SetResult(007);
            Task<int> task = tcs.Task;
            Console.Write(task.Result);


            //-----------------------------------
            var t = Run(() =>
            {
                Thread.Sleep(3000);
                return "wdnmd";
            });
            Console.WriteLine(t.Result);

            Task.Delay(5000).ContinueWith(ant => Console.WriteLine("延迟"));

        }
        static Task<TResult> Run<TResult>(Func<TResult> function) 
        {
            var tcs = new TaskCompletionSource<TResult>();
            new Thread(() =>
            {
                try
                {
                    tcs.SetResult(function());
                }
                catch (Exception ex)
                {

                    tcs.SetException(ex);
                }
            }).Start();
            return tcs.Task;
                            
        }

    }
}
